package com.hygj.service.impl;

import com.hygj.baseUtil.BaseDao;
import com.hygj.baseUtil.BaseServiceImpl;
import com.hygj.pojo.User;
import com.hygj.pojo.UserRole;
import com.hygj.service.UserRoleService;
import com.hygj.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

	@Resource
	UserRoleService userRoleService;
	@Resource
    UserService userService;
	
	
	@Resource(name = "userDao")
	@Override
	public void setDao(BaseDao<User> dao) {
		// TODO Auto-generated method stub
		super.setDao(dao);
	}
    
	/**
	 * 登录-根据用户名查询
	 */
	@Override
	public User findUserByLoginName(String username) {
		if(username == null){
			throw  new RuntimeException("用户名不能为空！");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("username", username);
		return (User) find("find", params);
	}

	/*
	 * uid 给用户赋予角色
	 */
	@Override
	public void grantUserRole(Integer uid, Integer[] rids) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid); // 用户角色关联表 uid
		delete("delete", uid);
		if (rids.length > 0 && uid > 0) {
			UserRole userRole;
			for (int i = 0; i < rids.length; i++) {
				userRole = new UserRole(rids[i], uid);
				userRoleService.insert(userRole);
			}
		}

	}

	/**
	 * 添加用户使用(和修改用户信息---调用)
	 * 
	 */
	@Override
	public int saveUserwithRole(User user, String roles) {
		int a;
		if (user.getUid() == null) {
			a = this.insert(user);
		} else {
			a = this.update("update", user);
			//userRoleService.delete("delete", user.getId());
		}
         // StringUtils.isNoneBlank 判断是否为空
		if (StringUtils.isNoneBlank(roles)) {
			//split() 方法用于把一个字符串分割成字符串数组。
			String[] r = roles.split(",");
			UserRole userRole;
			if (r.length > 0) {
				for (String _r : r) {
					//Integer.parseint()就是把整形对象Integer转换成基本数据类型int（整数）
					userRole = new UserRole(Integer.parseInt(_r), user.getUid());
					userRoleService.insert(userRole);
				}
			}
		}

		return a;
	}

    /**
     * 删除（或多条删除）
     */
	@Override
	public void delete(Integer[] ids) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(ids.length > 0){			
			for(Integer id: ids){
				//给userMapper 传id值  通过 params
				params.put("id", id);
				userRoleService.delete("delete", id);
				userService.delete("delete",id);
				
			}
			
		}
		
	}

}
